import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XTextField/XTextField.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/routers/pages.dart';
import '../../../components/BeautifulBGWidget/BeautifulBGWidget.dart';
import '../../../components/Tip/ToastUtils.dart';
import '../../../dart/base/model.dart';
import '../../../main.dart';

class ForgotPasswordPage extends BeautifulBGStatefulWidget {
  final String account;
  const ForgotPasswordPage({super.key, required this.account});

  @override
  State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState
    extends BeautifulBGStatefulState<ForgotPasswordPage> {
  TextEditingController accountController = TextEditingController();

  TextEditingController keyController = TextEditingController();
  TextEditingController verifyController = TextEditingController();

  TextEditingController passWordController = TextEditingController();

  TextEditingController verifyPassWordController = TextEditingController();

  var passwordUnVisible = true;

  var verifyPassWordUnVisible = true;

  var privateKey = true;

  var phoneNumber = false;

  //右滑返回
  double distance = 0;

  var sendVerify = false;

  Timer? timer;

  var dynamicId = '';
  //验证码重置时间
  var countDown = 60;
  //开始计时
  var startCountDown = false;

  late String _dynamicId = "";

  @override
  void initState() {
    accountController.text = widget.account;
    super.initState();
  }

  @override
  Widget buildWidget(BuildContext context) {
    return formLayout(context,
        showBack: true,
        showLogo: false,
        form: Padding(
          padding: const EdgeInsets.only(top: 10, left: 30, right: 30),
          child: Column(
            children: [
              Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  '找回密码',
                  style: TextStyle(fontSize: 28, fontWeight: FontWeight.w600),
                ),
              ),
              const SizedBox(height: 20),
              GestureDetector(
                child: SizedBox(
                  width: 375,
                  // height: 50,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      switchTips(privateKey, '私钥找回', 1),
                      switchTips(phoneNumber, '短信找回', 0),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 15),
              verifyForm(),
            ],
          ),
        ));
  }

  Widget switchTips(bool isChoice, String title, int x) {
    if (isChoice) {
      return GestureDetector(
          onTap: () {
            switchMode(x);
          },
          child: SizedBox(
            width: 88,
            height: 40,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  title,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: Color(0xFF366EF4),
                    fontSize: 14,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                  ),
                ),
                Container(
                  width: 16,
                  height: 3,
                  decoration: ShapeDecoration(
                    color: const Color(0xFF366EF4),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(999),
                    ),
                  ),
                ),
              ],
            ),
          ));
    } else {
      return GestureDetector(
        onTap: () {
          switchMode(x);
        },
        child: SizedBox(
          width: 88,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Color(0xFF15181D),
                  fontSize: 14,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

  Widget backToLogin() {
    return Positioned(
        top: 60,
        left: 20,
        child: GestureDetector(
          onTap: (() {
            backToLoginPage();
          }),
          child: XIcons.arrowBack32,
        ));
  }

  Widget verifyForm() {
    return Column(
      children: [
        XTextField.input(
            controller: accountController, title: '账号', hint: '请输入登录账号'),
        const SizedBox(height: 10),
        (privateKey)
            ? XTextField.input(
                controller: keyController, title: '私钥', hint: '请输入注册时保存的账户私钥')
            : XTextField.input(
                controller: verifyController,
                title: '手机号',
                hint: '请输入验证码',
                action: Container(
                  padding: const EdgeInsets.only(bottom: 5),
                  child: verificationCodeCountDown(),
                ),
              ),
        const SizedBox(height: 10),
        XTextField.input(
          controller: passWordController,
          title: '新密码',
          hint: '请输入新密码',
          obscureText: passwordUnVisible,
          action: IconButton(
              padding: const EdgeInsets.only(left: 40),
              onPressed: () {
                showPassWord();
              },
              icon: Icon(
                passwordUnVisible ? Icons.visibility_off : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              )),
        ),
        const SizedBox(height: 10),
        XTextField.input(
          controller: verifyPassWordController,
          title: '确认密码',
          hint: '请再次输入新密码',
          obscureText: verifyPassWordUnVisible,
          action: IconButton(
              padding: const EdgeInsets.only(left: 40),
              onPressed: () {
                showVerifyPassWord();
              },
              icon: Icon(
                verifyPassWordUnVisible
                    ? Icons.visibility_off
                    : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              )),
        ),
        const SizedBox(height: 20),
        comfirmSubmit(),
      ],
    );
  }

  // 构建修改密码页面
  // 分两种场景 1：忘记密码（未登录） 2：修改密码（已登录）
  List<Widget> buildModifyPasswordWidget() {
    var account = Storage.getList(Constants.account);
    List<Widget> widgets = [];
    String title = '忘记密码';
    title = '修改密码';

    widgets = [
      SizedBox(
        height: 75.h,
      )
    ];
    if (account != null) {
      accountController.text = account[0];
    } else {
      widgets.add(XTextField.input(
          controller: accountController, hint: "请输入用户名", title: "用户名"));
    }

    widgets.addAll([
      XTextField.input(
          controller: keyController, hint: "请输入注册时保存的账户私钥", title: "私钥"),
      XTextField.input(
          controller: passWordController,
          hint: "请输入密码",
          title: "密码",
          obscureText: passwordUnVisible,
          action: IconButton(
              onPressed: () {
                showPassWord();
              },
              icon: Icon(
                passwordUnVisible ? Icons.visibility_off : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              ))),
      XTextField.input(
          controller: verifyPassWordController,
          hint: "请再次输入密码",
          title: "确认密码",
          obscureText: verifyPassWordUnVisible,
          action: IconButton(
              onPressed: () {
                showVerifyPassWord();
              },
              icon: Icon(
                verifyPassWordUnVisible
                    ? Icons.visibility_off
                    : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              ))),
      SizedBox(
        height: 25.h,
      ),
      submitButton()
    ]);

    return widgets;
  }

  Widget submitButton() {
    return GestureDetector(
      onTap: () {
        submit();
      },
      child: Column(
        children: [
          Container(
            width: double.infinity,
            height: 60.h,
            decoration: BoxDecoration(
              color: XColors.themeColor,
              borderRadius: BorderRadius.circular(40.w),
            ),
            alignment: Alignment.center,
            child: Text(
              "提交",
              style: TextStyle(color: Colors.white, fontSize: 20.sp),
            ),
          ),
        ],
      ),
    );
  }

  //登录提交按钮
  Widget comfirmSubmit() {
    return GestureDetector(
      onTap: () {
        submit();
      },
      child: Container(
          width: 343,
          height: 45,
          padding: const EdgeInsets.only(top: 12),
          decoration: ShapeDecoration(
            color: XColors.themeColor,
            shape: RoundedRectangleBorder(
              side: const BorderSide(width: 1, color: Color(0xFFE7E8EB)),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: const Center(
            child: Text(
              '确认修改',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w600,
                height: 0.09,
              ),
            ),
          )),
    );
  }

  Widget verificationCodeCountDown() {
    TextStyle textStyle = TextStyle(color: XColors.themeColor, fontSize: 20.sp);
    String text = '发送验证码';
    if (startCountDown) {
      textStyle = TextStyle(color: Colors.grey, fontSize: 15.sp);
      text = "$countDown秒后重新发送";
    }
    return GestureDetector(
        onTap: () {
          if (!sendVerify) {
            getDynamicCode();
          }
        },
        child: Text(
          text,
          textAlign: TextAlign.end,
          style: textStyle,
        ));
  }

  void showPassWord() {
    passwordUnVisible = !passwordUnVisible;
    setState(() {});
  }

  void showVerifyPassWord() {
    verifyPassWordUnVisible = !verifyPassWordUnVisible;
    setState(() {});
  }

  void submit() async {
    if (accountController.text.isEmpty) {
      ToastUtils.showMsg(msg: "请输入用户名");
      return;
    }
    if (privateKey && keyController.text.isEmpty) {
      ToastUtils.showMsg(msg: "请输入注册时保存的账户私钥");
      return;
    }
    if (phoneNumber && verifyController.text.isEmpty) {
      ToastUtils.showMsg(msg: "请输入短信验证码");
      return;
    }
    if (passWordController.text != verifyPassWordController.text) {
      ToastUtils.showMsg(msg: "输入的两次密码不一致！");
      return;
    }
    if (passWordController.text.length < 6) {
      ToastUtils.showMsg(msg: "密码的长度不能小于6");
      return;
    }
    if (passWordController.text.length > 15) {
      ToastUtils.showMsg(msg: "密码的长度不能大于15");
      return;
    }
    RegExp regExp =
        RegExp(r'(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,15}');
    Match? match = regExp.firstMatch(passWordController.text);
    if (match == null) {
      ToastUtils.showMsg(msg: '密码必须包含：数字、字母、特殊字符');
      return;
    }
    ResultType result;
    if (privateKey) {
      result = await relationCtrl.auth.resetPassword(ResetPwdModel(
        account: accountController.text,
        password: passWordController.text,
        privateKey: keyController.text,
      ));
    } else {
      result = await relationCtrl.auth.resetPassword(ResetPwdModel(
        account: accountController.text,
        password: passWordController.text,
        dynamicId: _dynamicId,
        dynamicCode: verifyController.text,
      ));
    }

    if (result.success) {
      ToastUtils.showMsg(msg: '重置密码成功，请重新登录');
      RoutePages.back(context);
    } else {
      ToastUtils.showMsg(msg: result.msg);
    }
    setState(() {});
  }

  void backToLoginPage() {
    Navigator.pop(context);
  }

  void switchMode(int x) {
    if (x == 1) {
      privateKey = true;
      phoneNumber = false;
    } else {
      privateKey = false;
      phoneNumber = true;
    }
    setState(() {
    });
  }

  // 获得动态验证码
  Future<void> getDynamicCode() async {
    RegExp regex = RegExp(Constants.accountRegex);
    if (!regex.hasMatch(accountController.text)) {
      ToastUtils.showMsg(msg: "请输入正确的手机号");
      return;
    }
    if (sendVerify) {
      ToastUtils.showMsg(msg: "验证码已发送，请稍后再试");
      return;
    }
    startCountDown = true;
    countDown = 60;
    _dynamicId = '';

    var res = await relationCtrl.auth.dynamicCode(DynamicCodeModel.fromJson({
      'account': accountController.text,
      'platName': '资产共享云',
      'dynamicId': '',
    }));
    if (res.success && res.data != null) {
      _dynamicId = res.data!.dynamicId;
      sendVerify = true;
      startCountDownMethod();
    }
  }

  void startCountDownMethod() {
    if (timer != null) {
      if (timer!.isActive) {
        timerClose();
      }
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countDown <= 0) {
        timerClose();
      }
      countDown--;
    });
  }

  void timerClose() {
    timer?.cancel();
    timer = null;
    startCountDown = false;
    countDown = 60;
    sendVerify = false;
  }
}
